using Microsoft.EntityFrameworkCore;
using UpdaterManagement.Data;
using UpdaterManagement.Models;

var builder = WebApplication.CreateBuilder(args);

// 配置Kestrel服务器限制
builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 524288000; // 500MB
});

// Add services
builder.Services.AddControllersWithViews();

// 配置表单选项
builder.Services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 524288000; // 500MB
});
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseMySql("Server=comppay-test.czv6gmwbgqj6.rds.cn-northwest-1.amazonaws.com.cn;Database=updater_management;User=root;Password=1nPISwOg%fp^#E1F;", 
        new MySqlServerVersion(new Version(8, 0, 21))));

// Add authentication
builder.Services.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Logout";
        options.AccessDeniedPath = "/Account/Login";
    });

builder.Services.AddAuthorization();

var app = builder.Build();

// Configure pipeline
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.MapControllerRoute(
    name: "account",
    pattern: "Account/{action=Login}/{id?}",
    defaults: new { controller = "Account" });

app.MapControllerRoute(
    name: "department",
    pattern: "Department/{action=Index}/{id?}",
    defaults: new { controller = "Department" });

app.MapControllerRoute(
    name: "version",
    pattern: "Version/{action=Index}/{id?}",
    defaults: new { controller = "Version" });

app.MapControllerRoute(
    name: "deployedapplication",
    pattern: "DeployedApplication/{action=Index}/{id?}",
    defaults: new { controller = "DeployedApplication" });

app.MapControllerRoute(
    name: "user",
    pattern: "User/{action=Index}/{id?}",
    defaults: new { controller = "User" });

app.MapControllerRoute(
    name: "enterprise",
    pattern: "Enterprise/{action=Index}/{id?}",
    defaults: new { controller = "Enterprise" });

app.MapControllerRoute(
    name: "home",
    pattern: "Home/{action=Index}/{id?}",
    defaults: new { controller = "Home" });

// Initialize database
using (var scope = app.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
    
    try
    {
        // 确保数据库被创建
        context.Database.EnsureCreated();
        
        // 添加初始用户数据
        if (!context.Users.Any())
        {
            context.Users.AddRange(
                new User { Username = "admin", Password = "admin", RealName = "系统管理员", Role = "Admin", Email = "admin@example.com" },
                new User { Username = "user", Password = "user", RealName = "普通用户", Role = "User", Email = "user@example.com" }
            );
        }
        
        // 添加初始企业数据
        if (!context.Enterprises.Any())
        {
            context.Enterprises.AddRange(
                new Enterprise { Code = "2000000257", ErpNumber = "001608", Name = "西联测试*001608", Manager = "无" },
                new Enterprise { Code = "2000000329", ErpNumber = "000833", Name = "新峰（河南鲜风生活）", Manager = "青经理" }
            );
        }
        
        // 添加初始版本数据
        if (!context.VersionReleases.Any())
        {
            context.VersionReleases.AddRange(
                new VersionRelease { ProductName = "支付前置机", Version = "1.0.0", Description = "初始版本", DeployType = "0", IsActive = true, CreatedTime = DateTime.Now },
                new VersionRelease { ProductName = "支付前置机", Version = "1.1.0", Description = "功能更新", DeployType = "0", IsActive = true, CreatedTime = DateTime.Now },
                new VersionRelease { ProductName = "核心系统", Version = "2.0.0", Description = "核心系统初始版本", DeployType = "1", IsActive = true, CreatedTime = DateTime.Now },
                new VersionRelease { ProductName = "核心系统", Version = "2.1.0", Description = "核心系统更新", DeployType = "1", IsActive = true, CreatedTime = DateTime.Now },
                new VersionRelease { ProductName = "风控系统", Version = "1.5.0", Description = "风控系统", DeployType = "1", IsActive = true, CreatedTime = DateTime.Now },
                new VersionRelease { ProductName = "报表系统", Version = "3.0.0", Description = "报表系统", DeployType = "0", IsActive = true, CreatedTime = DateTime.Now }
            );
        }
        
        context.SaveChanges();
    }
    catch (Exception ex)
    {
        Console.WriteLine($"数据库初始化错误: {ex.Message}");
    }
}

app.Run();